package com.zhoukx.netty.hearbeat;


import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * 服务器端
 */
public class MyServer {

    public static void main(String[] args) {
        /*创建连个线程组*/
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {


            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 创建通道
                            ChannelPipeline pipeline = ch.pipeline();
                            // 加入一个netty提供IdleStateHandler
                            /**
                             * 说明:
                             *   IdleStateHandler是netty提供处理空闲状态的处理器
                             *   long readerIdleTime: 表示多长时间没有读,就会发送一个心跳检测包检测是否连接
                             *   long weiterIdleTIme: 表示多长时间没有写,就会发送一个心跳检测包检测是否连接
                             *   long allIdleTIme: 表示多长时间没有读写,就会发送一个心跳检测包检测是否连接
                             *
                             *   文档说明
                             *   triggers an{@link IdleStatetEvent} when a{@link Channel} has not performed
                             *   read,weite,or both operation for a while
                             *
                             *   当IdleStateEvent触发后,就会传递给管道的下一个handle去处理
                             *   通过调用(触发)下一个handler的userEventTiggered,在该方法中处理IdeStateEvent(读空闲,写空闲,读写空闲)
                             *
                             *
                             */

                            pipeline.addLast(new IdleStateHandler(7000, 5, 7000, TimeUnit.SECONDS));
                            // 加入一个空闲检测进一步处理的handler(自定义)
                            pipeline.addLast(new MyServerHandler());

                        }
                    });

            // 启动服务器
            ChannelFuture sync = bootstrap.bind(7008).sync();
            sync.channel().closeFuture().sync();
        } catch (Exception e) {
             e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
